/**
 *
 *
 * author  leson
 * date   2023-04-12
 * taskno:  0001
 * taskdesc: 简化代码风格
 * date:  2023-04-12
 * fixed: leson
 * taskno:  0002
 * taskdesc: 简化代码风格
 * date:  2023-04-13
 * fixed: lullu
 */
import typeInfo from "../action/index";
import { userQuery, userDelById, userAdd } from "../service/userService";

let initList = [];

function listReducer(state = initList, action) {
  switch (action.type) {
    case typeInfo.INITLIST:
      return action.payload; //payload就是一个集合
    case typeInfo.DELLIST:
      return state.filter((item) => item.id !== action.payload); //payload是一个编号(id)
    case typeInfo.ADDLIST:
      return [...state, action.payload]; //payload就是一个对象
    default:
      return state;
  }
}
export const addList = (payload) => {
  return {
    type: typeInfo.ADDLIST,
    payload,
  };
};
// export const asyncAddList = (payload) => {
//   return async (dispatch) => {
//     let res = await userQuery({ username: payload.username });
//     if (res.data.length) {
//       //判断用户名是存在
//       payload.cb({ code: 203, msg: "该用户名已经存在" });
//     } else {
//       let { data } = await userAdd({
//         username: payload.username,
//         userage: payload.userage,
//       });

//       dispatch(addList(data));
//       payload.cb({ code: 200, msg: "新增成功" });
//     }
//   };
// };
export const asyncAddList = (payload) => {
  return (dispatch) => {
    return new Promise(async (resolve) => {
      let res = await userQuery({ username: payload.username });
      if (res.data.length) {
        //判断用户名是存在
        resolve({
          code: 203,
          msg: "该用户名已经存在",
        });
      } else {
        let { data } = await userAdd({
          username: payload.username,
          userage: payload.userage,
        });
        dispatch(addList(data));
        resolve({
          code: 200,
          msg: "新增成功",
        });
      }
    });
  };
};

export const delList = (payload) => {
  return {
    type: typeInfo.DELLIST,
    payload,
  };
};

export const asyncDelList = (payload) => {
  return async (dispatch) => {
    await userDelById(payload); //调用接口删除数据
    dispatch(delList(payload)); //同步更新
  };
};

export const queryList = (payload) => {
  //数组
  return {
    type: typeInfo.INITLIST,
    payload,
  };
};
/**start taskno  0001***/
/*
export const asyncQueryList = (params) => {
  return async (dispatch) => {
    let { data } = await userQuery(params);
    dispatch(queryList(data));
  };
};
*/
export const asyncQueryList = (params) => async (dispatch) => {
  let { data } = await userQuery(params);
  dispatch(queryList(data));
  /**start taskno  0002***/ 
  console.log(data)
  /**start taskno  0002***/
};
/**end taskno  0001***/
export default listReducer;
